"""
MCP Inspector管理命令
"""
from django.core.management.base import BaseCommand
import os
import sys
import subprocess
import webbrowser
import time


class Command(BaseCommand):
    help = '启动MCP Inspector工具以测试和调试MCP服务'

    def add_arguments(self, parser):
        parser.add_argument(
            'url',
            nargs='?',
            default='http://127.0.0.1:8000/mcp/sse',
            help='MCP服务器URL, 默认为http://127.0.0.1:8000/mcp/sse'
        )
        parser.add_argument(
            '--inspector-port',
            type=int,
            default=6274,
            help='Inspector服务器端口, 默认为6274'
        )

    def handle(self, *args, **options):
        url = options['url']
        inspector_port = options['inspector_port']
        
        self.stdout.write(self.style.SUCCESS(f'正在启动MCP Inspector...'))
        self.stdout.write(f'目标MCP服务器URL: {url}')
        
        try:
            # 导入mcp模块
            from mcp.cli.main import main as mcp_main
            
            # 构建命令行参数
            inspector_args = ['inspector', '--port', str(inspector_port), url]
            
            # 启动Inspector
            self.stdout.write(self.style.SUCCESS(f'MCP Inspector启动成功!'))
            self.stdout.write(f'请在浏览器中访问: http://127.0.0.1:{inspector_port}')
            
            # 尝试自动打开浏览器
            try:
                time.sleep(1)  # 给Inspector一点时间启动
                webbrowser.open(f'http://127.0.0.1:{inspector_port}')
            except:
                pass  # 如果无法打开浏览器，忽略错误
            
            # 执行Inspector命令
            sys.argv = ['mcp'] + inspector_args
            mcp_main()
            
        except ImportError:
            self.stdout.write(self.style.ERROR('无法导入MCP模块，请确保已安装mcp[cli]'))
            self.stdout.write('尝试运行: pip install "mcp[cli]>=1.6.0"')
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'启动MCP Inspector时发生错误: {e}')) 